package cn.kust.serviceusercenter.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.kust.microtourismcommon.constant.CommonStatusEnum;
import cn.kust.microtourismcommon.constant.IdentityConstants;
import cn.kust.microtourismcommon.constant.UserMapperConstants;
import cn.kust.microtourismcommon.pojo.dto.MicroTourismUser;
import cn.kust.microtourismcommon.pojo.dto.ResponseResult;
import cn.kust.microtourismcommon.pojo.dto.UserNameAvatar;


import cn.kust.microtourismcommon.remote.ServiceOssClient;
import cn.kust.serviceusercenter.mapper.UserBaseMapper;
import cn.kust.serviceusercenter.mapper.UserMapper;
import cn.kust.serviceusercenter.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WY
 * @data 2022/7/20 16:59
 **/
@Service
@Slf4j
public class IUserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private ServiceOssClient serviceOssClient;


    @Override
    public ResponseResult<MicroTourismUser> loginOrRegister(String userPhone) {
        // 查询用户信息
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", userPhone);
        List<MicroTourismUser> microTourismUsers = userMapper.selectByMap(map);
        log.debug(microTourismUsers.size() == 0 ? "没有该用户,执行注册功能" : microTourismUsers.get(0).getUserPhone());

        // 判断用户信息是否存在
        if (microTourismUsers.size() == 0) {
            MicroTourismUser microTourismUser = new MicroTourismUser();
            String UserRandomCode = IdentityConstants.USER_RANDOMCODE + RandomUtil.randomString(6);
            microTourismUser.setUserName(IdentityConstants.USER_NEWNAME + UserRandomCode);
            microTourismUser.setUserGender((byte) 0);
            microTourismUser.setUserPhone(userPhone);
            microTourismUser.setUserState((byte) 0);
            LocalDateTime now = LocalDateTime.now();
            microTourismUser.setCreatedTime(now);
            microTourismUser.setUpdatedTime(now);
            userMapper.insert(microTourismUser);
            microTourismUsers = userMapper.selectByMap(map);
        }
//        从list中取出来的数据需要进行转化成json格式字符串，然后再将该json格式字符串转换成对象，这样就不会再出现报错情况，能成功遍历该list列表。
        String JO = JSON.toJSONString(microTourismUsers.get(0));
        MicroTourismUser microTourismUser = JSONObject.parseObject(JO, MicroTourismUser.class);
        return ResponseResult.success(microTourismUser);
    }

    @Override
    public ResponseResult getUserByPhone(String userPhone) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", userPhone);
        List<MicroTourismUser> passengerMicroTourismUsers = userMapper.selectByMap(map);

        if (passengerMicroTourismUsers.size() == 0) {
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST.getCode(), CommonStatusEnum.USER_NOT_EXIST.getValue());
        } else {
            MicroTourismUser microTourismUser = passengerMicroTourismUsers.get(0);
            return ResponseResult.success(microTourismUser);
        }
    }

    @Override
    public ResponseResult<UserNameAvatar> getUserNameAvatar(String userId) {
        QueryWrapper<UserNameAvatar> wrapper = new QueryWrapper();
        long userid = Long.parseLong(userId);
        wrapper.select("id as userId", "user_name", "avatar").eq("id", userid);
        UserNameAvatar userNameAvatar = userBaseMapper.selectOne(wrapper);
//        UserNameAvatar userNameAvatar = new UserNameAvatar();
//        userNameAvatar.setUserId(1L);
//        userNameAvatar.setUserName("用户");
//        userNameAvatar.setAvatar("头像");

        return ResponseResult.success(userNameAvatar);
    }

    @Override
    public ResponseResult getUserNameAvatarListById(List<Long> userIds) {

        QueryWrapper<UserNameAvatar> wrapper = new QueryWrapper();
        wrapper.select("id as userId", "user_name", "avatar").in("id", userIds);
        List<UserNameAvatar> resultList = userBaseMapper.selectList(wrapper);

        return ResponseResult.success(resultList);
    }

    @Override
    public ResponseResult<List<MicroTourismUser>> getUsersPage(int page, int size) {
        PageHelper.startPage(page, size);
        List<MicroTourismUser> userList = userMapper.selectList(new QueryWrapper<>());
        for (MicroTourismUser user : userList
        ) {
            System.out.println(user);
        }

        return ResponseResult.success(userList);
    }

    @Override
    public ResponseResult updateUserAvatar(MultipartFile file, String userId) {
        // 检验用户id是否存在与数据库里面
        Long userID = Long.parseLong(userId);
        QueryWrapper<MicroTourismUser> condition = new QueryWrapper<>();
        // SELECT COUNT( 1 ) FROM user WHERE (id = ?) limit 1 ;
        condition.eq("id", userID).last("limit 1");
        // 如果有这条数据那么 值是1
        Integer jugetId = userMapper.selectCount(condition);


        if (!UserMapperConstants.HAS_COUNT.equals(jugetId))
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST.getCode(), CommonStatusEnum.USER_NOT_EXIST.getValue());

        // 如果正确调用oss上传用户头像
        String avatarpath = serviceOssClient.uploadOssFile(file);
        //如果上传成功将头像路径上传数据库
        if (avatarpath != null && !avatarpath.isEmpty()) {
            MicroTourismUser user = new MicroTourismUser();
            user.setId(userID);
            user.setAvatar(avatarpath);
            userMapper.updateById(user);
            return ResponseResult.success();
        }


        return ResponseResult.fail(CommonStatusEnum.USER_UPLOAD_ERROR.getCode(), CommonStatusEnum.USER_UPLOAD_ERROR.getValue());
    }

    @Override
    public ResponseResult<String> updateUserBackground(MultipartFile file, String userId) {
        // 检验用户id是否存在与数据库里面
        Long userID = Long.parseLong(userId);
        QueryWrapper<MicroTourismUser> condition = new QueryWrapper<>();
        // SELECT COUNT( 1 ) FROM user WHERE (id = ?) limit 1 ;
        condition.eq("id", userID).last("limit 1");
        // 如果有这条数据那么 值是1
        Integer jugetId = userMapper.selectCount(condition);


        if (!UserMapperConstants.HAS_COUNT.equals(jugetId))
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST.getCode(), CommonStatusEnum.USER_NOT_EXIST.getValue());

        // 如果正确调用oss上传用户头像
        String backgroundpath = serviceOssClient.uploadOssFile(file);
        //如果上传成功将头像路径上传数据库
        if (backgroundpath != null && !backgroundpath.isEmpty()) {
            MicroTourismUser user = new MicroTourismUser();
            user.setId(userID);
            user.setBackgroundImg(backgroundpath);
            userMapper.updateById(user);
            return ResponseResult.success();
        }


        return ResponseResult.fail(CommonStatusEnum.USER_UPLOAD_ERROR.getCode(), CommonStatusEnum.USER_UPLOAD_ERROR.getValue());
    }

    @Override
    public ResponseResult deleteUserById(Long userId) {
        Integer index = userMapper.deleteById(userId);
        if (index == 1) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(CommonStatusEnum.USER_DELETE_ERROR.getCode(), CommonStatusEnum.USER_DELETE_ERROR.getValue());
    }

    @Override
    public ResponseResult updateUserInfo(Long userId, MicroTourismUser user) {

        // 先查询是否有这个用户id
        // 检验用户id是否存在数据库里面
        QueryWrapper<MicroTourismUser> condition = new QueryWrapper<>();
        // SELECT COUNT( 1 ) FROM user WHERE (id = ?) limit 1 ;
        condition.eq("id", userId).last("limit 1");
        // 如果有这条数据那么 值是1
        Integer jugetId = userMapper.selectCount(condition);

        if (!UserMapperConstants.HAS_COUNT.equals(jugetId))
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST.getCode(), CommonStatusEnum.USER_NOT_EXIST.getValue());

        //如果有再查询用户名是否有重复，没有重复才可以修改同时还要验证用户电话号号码
        QueryWrapper namequeryWrapper = new QueryWrapper<>();
        namequeryWrapper.eq("user_name", user.getUserName());
        //        判断用户名是否重复
        if (userMapper.selectCount(namequeryWrapper) > 0)
            return ResponseResult.fail(CommonStatusEnum.USER_NAME_ALL_READY_EXISTS_ERROR.getCode(), CommonStatusEnum.USER_NAME_ALL_READY_EXISTS_ERROR.getValue());


        //      判断电话号是否重复
        QueryWrapper phonequeryWrapper = new QueryWrapper<>();
        phonequeryWrapper.eq("user_phone", user.getUserPhone());
        if (userMapper.selectCount(phonequeryWrapper) > 0)
            return ResponseResult.fail(CommonStatusEnum.USER_PHONE_ALL_READY_EXISTS_ERROR.getCode(), CommonStatusEnum.USER_PHONE_ALL_READY_EXISTS_ERROR.getValue());


        Integer index = userMapper.updateById(user);

        if (index < UserMapperConstants.HAS_COUNT)
            return ResponseResult.fail(CommonStatusEnum.USER_UPDATE_ERROR.getCode(),CommonStatusEnum.USER_UPDATE_ERROR.getValue());
            // 修改成功返回提升

            return ResponseResult.success();
    }

    @Override
    public ResponseResult insertUser(MicroTourismUser user) {
        QueryWrapper namequeryWrapper = new QueryWrapper<>();
        namequeryWrapper.eq("user_name", user.getUserName());
        //        判断用户名是否重复
        if (userMapper.selectCount(namequeryWrapper) > 0)
            return ResponseResult.fail(CommonStatusEnum.USER_NAME_ALL_READY_EXISTS_ERROR.getCode(), CommonStatusEnum.USER_NAME_ALL_READY_EXISTS_ERROR.getValue());


        //      判断电话号是否重复
        QueryWrapper phonequeryWrapper = new QueryWrapper<>();
        phonequeryWrapper.eq("user_phone", user.getUserPhone());
        if (userMapper.selectCount(phonequeryWrapper) > 0)
            return ResponseResult.fail(CommonStatusEnum.USER_PHONE_ALL_READY_EXISTS_ERROR.getCode(), CommonStatusEnum.USER_PHONE_ALL_READY_EXISTS_ERROR.getValue());


        // 创建时间
        user.setCreatedTime(LocalDateTime.now());
        Integer index = userMapper.insert(user);


        if (index < UserMapperConstants.HAS_COUNT)
            return ResponseResult.fail(CommonStatusEnum.USER_UPDATE_ERROR.getCode(),CommonStatusEnum.USER_UPDATE_ERROR.getValue());
        // 修改成功返回提示

        return ResponseResult.success();
    }

}
